<template>
  <div class="uploading-file">
    <div class="person-img" @click="wxChooseImage">
        <img v-if="counter" :src="counter" class="identity-card" />
        <div  class="img-choose" v-else>
          <img src="../../static/img/issue.png" />
        </div>
    </div>
    <slot></slot>
</div>
</template>
<script>
import utils from '../utils'
import api from '../api'
export default {
  props: [ 'type' ],
  data () {
    return {
      counter: this.$store.state.uploadimg
    }
  },
  methods: {
    /* JSSDK 图片操作 */
    wxChooseImage: function () { // 图片选取
      var self = this
      this.$wechat.chooseImage({
        count: 1, // 默认9
        sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
        sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
        success: self.wxUploadImage
      })
    },
    wxUploadImage: function (res) { // 图片上传
      var self = this
      var localIds = res.localIds.toString()
      this.$wechat.uploadImage({
        localId: localIds.toString(),
        isShowProgressTips: 1, // 默认为1，显示进度提示
        success: self.downloadImage
      })
    },
    downloadImage: function (res) {
      var timeStamp = String(parseInt(Number(new Date()) / 1000))
      var tokenval = utils.AuthToken(timeStamp, this.$store.state.userkey)
      var serverId = res.serverId // 返回图片的服务器端ID
      this.$vux.loading.show({text: '图片上传中'})
      var params = {
        token: tokenval,
        timestamp: timeStamp,
        userId: this.$store.state.userID,
        imageType: this.type,
        wexinMediaId: serverId
      }
      api.upload(params).then(res => {
        if (res.status === '200') {
          this.$vux.loading.hide()
          this.counter = res.data.imageUrl
          this.$store.commit('changeIndexConf', {
            uploadimg: res.data.imageUrl
          })
        } else {
          this.$vux.toast.show({
            text: res.message,
            type: 'warn',
            width: '4rem'
          })
        }
      })
    }
  }
}
</script>

